#pragma once
#define FIFO_FILE "fifo"
#include<iostream>
#include<sys/types.h>
#include<sys/stat.h>
#include<string>
#include<fcntl.h>
#include<unistd.h>

class NamedFifo
{
public:
    NamedFifo(const std::string& path,const std::string& name)
    :_path(path) , _name(name)
    {
        //创建管道
        umask(0);
        _fifoname = _paht + "/" + _name;
        int n = mkififo(fifoname.c_str(),0666);
        if(n < 0)
        {
            std::cerr << "mkdir fifo error" << std::endl;
            exit(1);
        }
        std::cerr << "mkdir fifo success" << std::endl;
    }
    ~NamedFifo()
    {
        //删除管道
        int n = unlink(_fifoname);
        if(n == 0)
        {
            std::cout << "unlink fifo success" << std::endl;
            exit(1);
        }
        else
        {
            std::cerr << "unlink fifo error" << std::endl;
        }
    }
private:
    std::string _path;
    std::string _name;
    std::string _fifoname;
};

class FileOper
{
public:
    FileOper(const std::string& path,const std::string& name)
    :_path(path),_name(name)
    {
        _fifoname = _path + "/" + _name;
    }
    void OpenForRade()
    {
        //打开文件
        _fd = read(_fifoname.c_str(),O_RDONLY);
        if(_fd < 0)
        {
            std::cerr << "open fifo error" << std::endl;
            exit(1);
        }
        std::cout << "open fifo success" << std::endl;
    }
    void OpenForWrite()
    {
        _fd = read(_fifoname.c_str(),O_WRONLY);
        if(_fd < 0)
        {
            std::cerr << "open fifo error" << std::endl;
            exit(1);
        }
        std::cout << "open fifo success" << std::endl;
    }

    void Read()
    {
        while(true)
        {
            char buffer[1024];
            int number = read(_fd,buffer,sizeof(buffer) - 1);
            if(number > 0)
            {
                std::cout << "client say# " << buffer << std::endl;
            }
            else if(number == 0)
            {
                std::cout << "client quite?" << number << std::endl;
                break;
            }
            else
            {
                std::cerr <<"client error" << std::endl;
                break;
            }
        }
    }
    void Write()
    {
        std::string massage;
        int cnt = 1;
        pid_t id = getpid();
        while(true)
        {
            std::cout << "please Enter#";
            std::getline(std::cin,massage);
            massage += " ,cnt = " + std::to_string(cnt++) + " ,id = " + std::to_string(id);
            int number = write(fd,massage.c_str(),massage.size());
        }
    }
    void close()
    {
        close(_fd);
    }
    ~FileOper()
    {

    }
private:
    std::string _path;
    std::string _name;
    std::string _fifoname;
    int fd;
}